<?php
/**
 * @software         [JiJinCMS]
 * @author           [上海集锦信息科技有限公司]
 * @website          [http://www.jijinweb.com]
 * @email            [sunny@jijinweb.com]
 **/
namespace app\admin\controller;
use think\facade\View;
use app\admin\model\RoleModel;
use think\facade\Db;
use think\facade\Request;
class FeedbackField extends \app\admin\controller\Admin{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->model=new \app\admin\model\FeedbackFieldModel();
        $this->validate=new \app\admin\validate\FeedbackFieldValidate();
       //字段类型
       $fieldtype_inc=array(
           "varchar"=>              "字符型0-255字节(varchar)",
           "char"=>                 "定长字符型0-255字节(char)",
           "text"=>                 "小型字符型(text)",
           "mediumtext"=>           "中型字符型(mediumtext)",
           "longtext"=>             "大型字符型(longtext)",
           "tinyint"=>              "小数值型(tinyint)",
           "smallint"=>             "中数值型(smallint)",
           "int"=>                  "大数值型(int)",
           "bigint"=>               "超大数值型(bigint)",
           "float"=>                "数值浮点型(float)",
           "double"=>               "数值双精度型(double)",
           "date"=>                 "日期型(date)",
           "datetime"=>             "日期时间型(datetime)",
       );
       View::assign("fieldtype_inc",$fieldtype_inc);
       //表单类型
       $formtype_inc=array(
           "text"=>              "单行文本框(text)",
           "password"=>          "密码框(password)",
           "select"=>            "下拉框(select)",
           "radio"=>             "单选框(radio)",
           "checkbox"=>          "复选框(checkbox)",
           "morevalue"=>         "多值字段(morevalue)",    
           "textarea"=>          "多行文本框(textarea)",
           "date"=>              "日期(date)",
       );  
       View::assign("formtype_inc",$formtype_inc);
       //常用正则
       $pattern_inc=array(
           "/^[0-9.-]+$/"=>                             "数字",
           "/^[0-9-]+$/"=>                              "整数",
           "/^[a-z]+$/i"=>                              "字母",
           "/^[0-9a-z]+$/i"=>                           "数字+字母",
           "/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/"=>          "E-mail",
           "/^[0-9]{5,20}$/"=>                          "QQ",
           "/^http:\/\//"=>                             "超级链接",
           "/^(1)[0-9]{10}$/"=>                         "手机号码",
           "/^[0-9-]{6,13}$/"=>                         "电话号码",
       );   
       View::assign("pattern_inc",$pattern_inc);
       //系统字段（禁止删除）
       $this->systemfield_inc=["title","name","mobile","email"];
       View::assign("systemfield_inc",$this->systemfield_inc);
    }    
    //
    public function index(){
        $data=$this->model->order('sort asc,field_id asc')->select();
        View::assign('data', $data);
        return View::fetch();
    }
    public function add(){
        if(request()->isPost()){
            $data=$this->request->param();
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //验证字段在数据表里是否存在了
            if($this->model->field_exists("feedback",$data['field'])){
                $this->error("该字段在数据表已存在");
            }
            //增加字段
            $field = array(
                'tablename' => config('database.connections.mysql.prefix'). "feedback",
                'fieldname' => $data['field'],
                'fieldlen' => $data['fieldlen'],
                'defaultval' => $data['defaultval'],
            );  
            $this->model->addFieldSql($data['fieldtype'],$field);
            //更新htmlcode
            $data['htmlcode']=$this->model->createFieldHtmlCode($data);
            //如果是morevalue需要对defaultvalue进行加工
            if($data["formtype"]=="morevalue"){
                $data["defaultval"]=$this->model->detailMorevalueDefaultval($data);
            }   
            //
            $data['savefun_trigger']=implode("|",$data['savefun_trigger']);
            if($data['savefun_trigger']){
                $data['savefun_trigger']="|".$data['savefun_trigger']."|";
            }  
            $this->model->save($data);
            $lastId=$this->model->field_id;
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$lastId,$this->request->param());
            $this->success("添加成功",url('index'));
        }else{          
            return View::fetch();
        }
    } 
    public function update(){
        if(request()->isPost()){
            $data=$this->request->param();
            //增加field_id字段校验
            $this->validate->append('field_id','require');
            //
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //查询这个字段在table_field是否存在，要查当前table_id并table_id排除field_id
            $where[]=["field","=",$data["field"]];         
            $where[]=["field_id","<>",$data["field_id"]];     
            $HasTableField=$this->model->where($where)->count();
            if($HasTableField){
                $this->error("字段已存在");
            }
            //
            $r=$this->model->find($data['field_id']);
            //完整表名获取 判断主表 还是副表
            if ($data['field'] != $r['field']&& $this->model->field_exists("feedback", $data['field'])) {
                $this->error("该字段在数据表已存在");
            }
            $field = array(
                'tablename' => config('database.connections.mysql.prefix'). "feedback",
                'newfieldname' => $data['field'],
                'oldfieldname' => $r['field'],
                'fieldlen' => $data['fieldlen'],
                'defaultval' => $data['defaultval'],
            );            
            $this->model->editFieldSql($data['fieldtype'],$field);
            //更新htmlcode
            $data['htmlcode']=$this->model->createFieldHtmlCode($data);
            //如果是morevalue需要对defaultvalue进行加工
            if($data["formtype"]=="morevalue"){
                $data["defaultval"]=$this->model->detailMorevalueDefaultval($data);
            }       
            $this->model->update($data);
            //更新modeltemp
            $cat=Db::name("feedback_cat")->select();
            $CatModel=new \app\admin\model\FeedbackCatModel();
            foreach($cat as $v){
                $CatModel->updateModelTemp($v['catid']);
            }     
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$data['field_id'],$this->request->param());
            $this->success("修改成功",url('index'));
        }else{
            $field_id=Request::param("field_id");
            $r=$this->model->find($field_id);
            View::assign("r",$r);
            return View::fetch();
        }
    }    
    //删除
    public function delete(){
        $field_id=Request::param('field_id',0,"intval");
        $r=$this->model->find($field_id);
        if(!$r){$this->error("数据不存在");}
        //判断是否允许删除
        if (in_array($r['field'],$this->systemfield_inc)){
            $this->error("系统字段不允许被删除!");
        }
        $this->model->deleteFieldSql($r['field'],"feedback");
        $this->model->where("field_id",$field_id)->delete();
        //更新modeltemp
        $cat=Db::name("feedback_cat")->select();
        $CatModel=new \app\admin\model\FeedbackCatModel();
        foreach($cat as $v){
            $CatModel->updateModelTemp($v['catid']);
        }     
        $this->UserLogModel->add(Request()->action(),$this->model->getName(),$field_id,$this->request->param());
        $this->success("删除成功");
    }
    //更新排序
    public function updateSort(){
        $id=Request::param('field_id');
        $sort=Request::param('sort');
        foreach($id as $key=>$v){
            $this->model->update(['field_id'=>$id[$key],'sort'=>$sort[$key]]);
        }
        $this->success("设置成功");
    }    
}
